const {ipcRenderer} = require('electron');
// const ipcRenderer = electron.ipcRenderer;
const io = require('./io');
let publicfunc = require('./publicfunc');

let CurrentMusicPage = 0;
let MusicPageCount = 20;
let AudioMusicFiles;
let MusicTagTree;
let CurrentMusicMainTagButton;
let CurrentMusicChildTagButton;
let MusicFlags = true;
let MusicKey = 'music';


function OnMusicPageChange(page, co0unt) {
    CurrentMusicPage = page;
    MusicPageCount = count;
    publicfunc.RequestSearch(page, count, false, MusicFlags);
}

function OnMusicMainTagChange(btn) {
    if (CurrentMusicMainTagButton != undefined) {
        CurrentMusicMainTagButton.removeClass('active');
    }
    CurrentMusicMainTagButton = btn;
    CurrentMusicMainTagButton.addClass('active');
}

function MusicChildTagChange(btn) {
    if (CurrentMusicChildTagButton != undefined) {
        CurrentMusicChildTagButton.removeClass('active');
    }
    CurrentMusicChildTagButton = btn;
    CurrentMusicChildTagButton.addClass('active');
}

function RequestMusicSearch(isRefresh, isMusic) {

    publicfunc.RequestSearch(CurrentMusicPage, MusicPageCount, isRefresh, isMusic);
}

function RequestMusicNewTag(tag, isMusic) {    
    publicfunc.RequestNewTag(CurrentMusicMainTagButton.text(),CurrentMusicChildTagButton.text(),tag,isMusic);
}
    io.onwebsocket('search-{0}'.format(MusicKey), (data) => {
        AudioMusicFiles = data.results;
        // if (AudioMusicFiles == null) {
        //     return;
        // }
        publicfunc.UpdateResoucesShown(AudioMusicFiles, data.index, MusicTagTree, data.size, MusicPageCount, OnMusicPageChange, MusicFlags,'music');   
        if( $('#resourceList-music').find('.music-check').length > 0){
            $('#mu_import').removeClass('disabled')
        }
    });
    io.onwebsocket('gettaglist-{0}'.format(MusicKey), (data) => {
        MusicTagTree = data;
        if (MusicTagTree == null) {
            return;
        }
        publicfunc.UpdateMainTagsShown(MusicTagTree, OnMusicMainTagChange, MusicChildTagChange, RequestMusicSearch, MusicFlags);
    });
    publicfunc.RegistWS(MusicFlags);

function DownloadMusics(ids) {
    let files = new Array();
    for (let i = 0; i < ids.length; i++) {
        let file = publicfunc.GetFile(AudioMusicFiles, ids[i]);
        if (file != null) {
            files.push(file);
        }
    }
    ipcRenderer.send('downloadall', { baseurl: io.geturl(), files: files });
}

publicfunc.RegistClickEvents(MusicFlags, DownloadMusics, RequestMusicSearch, RequestMusicNewTag);
